import java.util.Arrays;

/**
 * @Author ZhangCuirong
 * @Date 2025/8/12 12:36
 * @description:
 */
public class Solution59 {
    public int[][] generateMatrix(int n) {
        int[][] res = new int[n][n];
        int index = 1;
        int left = 0, right = n - 1, top = 0, bottom = n - 1;
        while (left <= right && top <= bottom) {
            if (left <= right) {
                for (int i = left; i <= right; i++) {
                    res[top][i] = index++;
                }
            }
            top++;
            if (top <= bottom) {
                for (int i = top; i <= bottom; i++) {
                    res[i][right] = index++;
                }
            }
            right--;
            if (left <= right) {
                for (int i = right; i >= left; i--) {
                    res[bottom][i] = index++;
                }
            }
            bottom--;
            if (top <= bottom) {
                for (int i = bottom; i >= top; i--) {
                    res[i][left] = index++;
                }
            }
            left++;
        }
        return res;
    }

    public static void main(String[] args) {
        Solution59 solution = new Solution59();
        int[][] res = solution.generateMatrix(3);
        for (int i = 0; i < res.length; i++) {
            System.out.println(Arrays.toString(res[i]));
        }
    }
}
